package cdu.sl.interceptor;

import cdu.sl.common.utils.BaseContext;
import cdu.sl.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");

        log.info("开始校验token...");
        // 如果请求头中没有token，则返回未授权错误
        if (!StringUtils.hasText(token)) {
            log.warn("请求未携带token: {}", request.getRequestURI());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        
        // 验证token
        if (!jwtUtils.validateToken(token)) {
            log.warn("token无效: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        log.info("token校验通过...");
        // 从token中获取用户ID并设置到请求属性中
        Long userId = jwtUtils.getUserIdFromToken(token);
        // 将用户id存入ThreadLocal
        BaseContext.setCurrentId(userId);
        request.setAttribute("userId", userId);
        
        return true;
    }

} 